package com.chezai.client.dao.manager;

import com.chezai.client.bean.PeriodRecord;
import com.chezai.client.dao.DaoManager;
import com.chezai.client.dao.PeriodRecordDao;
import com.chezai.client.global.Const;
import com.chezai.client.utils.DateUtil;
import com.chezai.client.utils.Util;
import com.google.gson.Gson;
import com.jx.driving.domain.GnssPackage;
import com.jx.driving.request.domain.LocationAttachement;
import com.jx.driving.transmission.Terminal0x0203Transmission;
import com.orhanobut.logger.Logger;

import java.util.List;

/**
 * 学时记录数据操作管理类
 * Created by likunyang on 2017/8/24.
 */

public class PeriodRecordDaoManager {
    private static PeriodRecordDaoManager newInstance;
    private final PeriodRecordDao dao;

    private PeriodRecordDaoManager() {
        dao = DaoManager.getInstance().getDaoSession().getPeriodRecordDao();
    }

    public static PeriodRecordDaoManager getInstance() {
        if (newInstance == null) {
            newInstance = new PeriodRecordDaoManager();
        }
        return newInstance;
    }

    public static String parseListToJson(List<LocationAttachement> list) {
        String json = null;
        try {
            Gson gson = new Gson();
            json = gson.toJson(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;

    }

    // 获取教学日志编号
    public int getSequence(String date) {
        List<PeriodRecord> record = dao.queryBuilder()
                .where(PeriodRecordDao.Properties.CreatDate.eq(date))
                .orderDesc(PeriodRecordDao.Properties.SequenceNumber)
                .limit(1)
                .list();
        if (record.size() == 0) {
            return 0;
        }
        return Integer.parseInt(record.get(0).getSequenceNumber());
    }

    public Terminal0x0203Transmission periodRecordTo0203Trans(PeriodRecord periodRecord) {
        if (periodRecord != null) {
            Terminal0x0203Transmission transmission = new Terminal0x0203Transmission();
            transmission.setRecordTime(periodRecord.getRecordTime());//记录产生时间HHmmss
            transmission.setRecordNo(periodRecord.getRecordNo());
            transmission.setType(periodRecord.getUploadType());//上报类型
            transmission.setUserNo(periodRecord.getStuUnifiedNum());
            transmission.setCoachNo(periodRecord.getCoachUnifiedNum());
            transmission.setCourse(periodRecord.getCourse());//课程编号
            transmission.setClassId(periodRecord.getClassId());//课堂ID
            transmission.setRecordStatus(periodRecord.getStatus());//记录状态 0：正常记录；1：异常记录
            transmission.setMaxSpeed(periodRecord.getMaxSpeed());
            transmission.setMileage(periodRecord.getMileage());
            transmission.setGnss(Util.parseJsonToObject(periodRecord.getGnss(), GnssPackage.class));
            List<LocationAttachement> locationAttachements = Util.parseJsonToLocationAttachements(periodRecord.getAttachement());
            transmission.setAttachementList(locationAttachements);
            return transmission;
        }
        return null;
    }

    public PeriodRecord findPeriodRecordById(long periodRecord_Id) {
        PeriodRecord periodRecord = dao.load(periodRecord_Id);
        return periodRecord;
    }

    public long insertPeriodRecord(Terminal0x0203Transmission transmission, String sequenceNumber, long classRecordId) {
        PeriodRecord periodRecord = new PeriodRecord();
        periodRecord.setTryCount(0);
        periodRecord.setUploadState(Const.UPLOAD_FAILED);
        periodRecord.setRecordNo(transmission.getRecordNo());
        periodRecord.setUploadType(transmission.getType());
        periodRecord.setStuUnifiedNum(transmission.getUserNo());
        periodRecord.setCoachUnifiedNum(transmission.getCoachNo());
        periodRecord.setClassId(transmission.getClassId());
        periodRecord.setRecordTime(DateUtil.timestampStr("HHmmss"));
        periodRecord.setCourse(transmission.getCourse());
        periodRecord.setStatus(transmission.getRecordStatus());
        periodRecord.setMaxSpeed(transmission.getMaxSpeed());
        periodRecord.setMileage(transmission.getMileage());
        periodRecord.setCreatDate(DateUtil.timestampStr("yyMMdd"));
        periodRecord.setSequenceNumber(sequenceNumber);
        String gnssJson = Util.parseObjectToJson(transmission.getGnss());
        periodRecord.setGnss(gnssJson);
        periodRecord.setAttachement(parseListToJson(transmission.getAttachementList()));
        periodRecord.setClassRecordId(classRecordId);
        long id = dao.insert(periodRecord);
        return id;
    }

    public void updatePeriodRecordUploadState(long periodRecord_Id, int uploadState) {
        PeriodRecord periodRecord = findPeriodRecordById(periodRecord_Id);
        if (periodRecord != null) {
            periodRecord.setUploadState(uploadState);
            dao.update(periodRecord);
        }
    }

    /**
     * 查找未上报成功的学时
     * 查询条件为：
     * Select * from PERIOD_RECORD where CLASS_RECORD_ID = classRecordId and UPLOAD_STATE=0 and(TRY_COUNT <=3 or TRY_COUNT IS NULL);
     *
     * @param classRecordId 当前课程记录ID
     * @return
     */
    public List<PeriodRecord> findCanUploadFailedPeriodRecord(long classRecordId) {
        List<PeriodRecord> periodRecords = dao.queryBuilder()
                .where(PeriodRecordDao.Properties.ClassRecordId.eq(classRecordId)
                        , PeriodRecordDao.Properties.UploadState.eq(Const.UPLOAD_FAILED)
                        , PeriodRecordDao.Properties.TryCount.le(Const.TRY_COUNT))
                .list();
        return periodRecords;
    }

    public List<PeriodRecord> findAllUploadFailedPeriodRecord(long classRecordId) {
        List<PeriodRecord> periodRecords = dao.queryBuilder()
                .where(PeriodRecordDao.Properties.ClassRecordId.eq(classRecordId)
                        , PeriodRecordDao.Properties.UploadState.eq(Const.UPLOAD_FAILED))
                .list();
        return periodRecords;
    }

    public void update(PeriodRecord periodRecord) {
        dao.update(periodRecord);
    }

    public void testInsert() {
        int i = 0;
        while (i <= 100) {
            PeriodRecord periodRecord = new PeriodRecord();
            periodRecord.setTryCount(0);
            periodRecord.setUploadState(Const.UPLOAD_FAILED);
            periodRecord.setRecordNo("test");
            periodRecord.setUploadType((short) 1);
            periodRecord.setStuUnifiedNum("stuunifiednum");
            periodRecord.setCoachUnifiedNum("coachUnifiedNum");
            periodRecord.setClassId(1);
            periodRecord.setRecordTime(DateUtil.timestampStr("HHmmss"));
            periodRecord.setCourse("testCourse");
            periodRecord.setStatus((short) 1);
            periodRecord.setMaxSpeed(2);
            periodRecord.setMileage(100);
            periodRecord.setCreatDate(i % 3 == 0 ? "180413" : i % 3 == 1 ? "170413" : "180420");
            periodRecord.setSequenceNumber("123");
            periodRecord.setGnss("testGnss");
            periodRecord.setAttachement("testAttach");
            periodRecord.setClassRecordId(1);
            long j = dao.insert(periodRecord);
            Logger.t("Insert").e("periodRecord " + j);
            i++;
        }
    }

    //删除三天以前的数据
    public void deleteTimeOutData() {
        try {
            String current = DateUtil.getPastDate(Const.DATA_TIME_OUT_DAY, DateUtil.sf28);
            List<PeriodRecord> list = dao.queryBuilder().where(PeriodRecordDao.Properties.CreatDate.le(current)).list();
            dao.deleteInTx(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
